import type { AxiosRequestConfig } from "axios";
import type { PendingRecord } from "./types";

const pendingMap = new Map<string, PendingRecord>();
const MAX_PENDING_AGE = 1000 * 60; // 1分钟

function getPendingKey(config: AxiosRequestConfig): string {
  const { url, method = "get", params, data } = config;
  return [url, method.toUpperCase(), JSON.stringify(params), typeof data === "string" ? data : JSON.stringify(data)].join("|");
}

export function addPending(config: AxiosRequestConfig) {
  const key = getPendingKey(config);
  const now = Date.now();

  // 清理过期请求
  pendingMap.forEach((record, k) => {
    if (now - record.timestamp > MAX_PENDING_AGE) {
      pendingMap.delete(k);
    }
  });

  // 如果已存在相同请求
  if (pendingMap.has(key)) {
    const existing = pendingMap.get(key)!;
    existing.controller.abort(`重复请求被取消: ${key}`);
    pendingMap.delete(key);
  }

  const controller = new AbortController();
  config.signal = controller.signal;
  pendingMap.set(key, { controller, timestamp: now });
}

export function removePending(config: AxiosRequestConfig) {
  const key = getPendingKey(config);
  pendingMap.delete(key);
}

export function cancel(config: AxiosRequestConfig) {
  const key = getPendingKey(config);
  if (pendingMap.has(key)) {
    pendingMap.get(key)?.controller.abort("手动取消请求");
    pendingMap.delete(key);
  }
}

export function cancelAll() {
  pendingMap.forEach(record => {
    record.controller.abort("手动取消所有请求");
  });
  pendingMap.clear();
}
